<template>
    <div class="cover-upload">
        <el-upload name="file" :show-file-list="false" accept=".PNG,.png,.jpg,.JPG,.jpeg,.JPEG,.gif,.GIF,.bmp,.BMP"
            :multiple="false" :http-request="uploadImage">
            <div class="cover-upload-btn">
                <template v-if="localFile">
                    <img :src="localFile" />
                </template>
                <template v-else>
                    <img :src="(imageUrlPrefix ? imageUrlPrefix : proxy.globalInfo.imageUrl) + modelValue.imageUrl"
                        v-if="modelValue && modelValue.imageUrl" />
                    <span class="iconfont" v-else>
                        <el-icon size="50">
                            <Plus />
                        </el-icon>
                    </span>
                </template>
            </div>
        </el-upload>
    </div>
</template>

<script setup>
import { getCurrentInstance, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router';
const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()
const props = defineProps({
    imageUrlPrefix: {
        type: String,
    },
    modelValue: {
        type: Object,
        default: null
    }
})

//本地预览图片
const localFile = ref(null)

const emit = defineEmits()

//自定义上传图片方法
const uploadImage = async (file) => {
    file = file.file
    let img = new FileReader()
    img.readAsDataURL(file)
    img.onload = ({ target }) => {
        localFile.value = target.result
    }
    emit("update:modelValue", file)
}
</script>
<style scoped lang="scss">
.cover-upload {
    .cover-upload-btn {
        background-color: #f3f3f3;
        width: 150px;
        height: 150px;
        display: flex;
        align-items: center;
        justify-content: center;

        .iconfont {
            color: #ddd;
        }

        img {
            width: 100%;
        }
    }
}
</style>